/**@FILE:WxApiService.java
 * @AUTHOR:qingsheng.zheng
 * @DATE:2015-5-20 上午11:38:58*/
package com.xf.toy.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.xf.pub.exception.ServiceException;
import com.xf.pub.tool.HttpClientUtil;
import com.xf.pub.tool.SignUtil;
import com.xf.toy.service.UserService;
import com.xf.toy.service.WxApi;

/*******************************************
 * @COMPANY:alibaba
 * @CLASS:WxApiService
 * @DESCRIPTION:
 * @AUTHOR:qingsheng.zheng
 * @VERSION:v1.0
 * @DATE:2015-5-20 上午11:38:58
 *******************************************/
@Service("wxapi")
public class WxApiServiceImpl implements WxApi {
	private String appid = "wx3dd15d5609a3a8bd";
	private String appsecret = "06e8e169b671e15dc98ce1fd06a19ac0";
	private Logger logger=LoggerFactory.getLogger(this.getClass());
	@Resource(name="userService")
	private UserService userService;

	@Override
	public void signUrl(String signature, String timestamp, String nonce,
			String echostr) {
		
		Boolean isSuccess=SignUtil.checkSignature(signature, timestamp, nonce);
		if(!isSuccess)
			throw new ServiceException(20001L);
	}

	public  String oAuth2Url(String redirect_uri) {
		try {
			redirect_uri = java.net.URLEncoder.encode(redirect_uri, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String oauth2Url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
				+ this.appid
				+ "&redirect_uri="
				+ redirect_uri
				+ "&response_type=code&scope=snsapi_base&state=success#wechat_redirect";
		return oauth2Url;
	}

	public JSONObject getAccessTokenInfo(String code) {
		  StringBuilder url = new StringBuilder();  
	        url.append("https://api.weixin.qq.com/sns/oauth2/access_token?");  
	        url.append("appid=" + appid);  
	        url.append("&secret=").append(this.appsecret);  
	        url.append("&code=").append(code);  
	        url.append("&grant_type=authorization_code");
	        String result="";
		try {
			
			result=HttpClientUtil.get(url.toString(), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		JSONObject data=JSONObject.fromObject(result);
		return data;
	}
	
	public JSONObject getToken()
	{
		 StringBuilder url = new StringBuilder();  
		 String result="";
		 url.append("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=")
		 .append(this.appid).append("&secret=").append(this.appsecret);
		 try {
			result= HttpClientUtil.get(url.toString(), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		 JSONObject data=JSONObject.fromObject(result);
			return data;
	}

}
